﻿using Common.BaseLibrary.Authorization;
using DepartmentWork.Migrator.Data;
using DepartmentWork.Model;
using DepartmentWork.Platform.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DepartmentWork.Platform.Areas.DepartmentArea.Controllers
{
    public class OvertimeController : BaseController
    {

        /// <summary>
        /// 展示加班列表
        /// </summary>
        /// <param name="flag"></param>
        /// <param name="info"></param>
        /// <returns></returns>
        public ActionResult Index(string flag = "", string flagInfo = "")
        {
            ViewBag.Flag = flag;
            ViewBag.FlagInfo = flagInfo;

            #region 设置分页

            var pageSizeExecute = this.Request["pageSizeExecute"] == null ? 10 : int.Parse(Request["pageSizeExecute"]);
            var pageIndexExecute = this.Request["pageIndexExecute"] == null ? 1 : int.Parse(Request["pageIndexExecute"]);

            ViewData["pageIndexExecute"] = pageIndexExecute;
            ViewData["pageSizeExecute"] = pageSizeExecute;

            var pageSize = this.Request["pageSizeFinish"] == null ? 10 : int.Parse(Request["pageSizeFinish"]);
            var pageIndex = this.Request["pageIndexFinish"] == null ? 1 : int.Parse(Request["pageIndexFinish"]);

            ViewData["pageIndexFinish"] = pageIndex;
            ViewData["pageSizeFinish"] = pageSize;

            #endregion
            List<PROJECT_DESK_WORKTIME> OwnWorktime = new List<PROJECT_DESK_WORKTIME>();//个人加班
            List<ProjectDeskWorkTimeViewModel> ViewOwnworktime = new List<ProjectDeskWorkTimeViewModel>();//个人加班

            List<PROJECT_DESK_WORKTIME> AllWorktime = new List<PROJECT_DESK_WORKTIME>();//本空间下全员的加班
            List<ProjectDeskWorkTimeViewModel> ViewAllworktime = new List<ProjectDeskWorkTimeViewModel>();//全体加班记录

            List<PROJECT_DESK_WORKTIME> OverWorkTime = new List<PROJECT_DESK_WORKTIME>();//待审批的加班记录
            List<ProjectDeskWorkTimeViewModel> ViewOverWorkTime = new List<ProjectDeskWorkTimeViewModel>();//待审批的加班记录

            #region 若不是匿名用户则读取该用户所在的团队空间项目；如果是匿名用户则读取所有团队空间的项目
            if (CurrentUser.UserID.Length != 0)//如果数据库中存在这个用户，说明这个用户是科室人员
            {

                //根据登录ID找到团队空间ID
                Guid teamSpaceId = userTeamsapceRepository.GetModel(r => r.USER_ID == new Guid(CurrentUser.UserID)).FirstOrDefault().TEAMSPACE_ID;
                #region 个人加班记录
                OwnWorktime = projectdeskworktimeRepository.GetModel(r => r.WORKTIME_NAMEID == new Guid(CurrentUser.UserID)).OrderByDescending(r => r.WORKTIME_TIME).ToList();//个人加班信息
                for (int i = 0; i < OwnWorktime.Count; i++)
                {
                    Guid id = OwnWorktime[i].WORKTIME_NAMEID;
                    var username = userRepository.Find(r => r.USER_ID == id).DISPLAY_NAME.ToString();//要权限
                    Guid ID = OwnWorktime[i].WORKTIME_OVERNAME;
                    var USERNAME = "";
                    USER_INFO uerinfo = userRepository.Find(r => r.USER_ID == ID);
                    if (uerinfo != null)
                    {
                        USERNAME = uerinfo.DISPLAY_NAME;
                    }

                    ProjectDeskWorkTimeViewModel viewmodel = new ProjectDeskWorkTimeViewModel();
                    viewmodel.worktime_name = username;
                    viewmodel.worktime_time = OwnWorktime[i].WORKTIME_TIME;
                    viewmodel.worktime_cause = OwnWorktime[i].WORKTIME_CAUSE;
                    viewmodel.worktime_duration = OwnWorktime[i].WORKTIME_DURATION;
                    viewmodel.worktime_id = OwnWorktime[i].WORKTIME_ID;
                    viewmodel.worktime_day = OwnWorktime[i].WORKTIME_DAY.ToString();
                    viewmodel.worktime_time_time = OwnWorktime[i].WORKTIME_TIME_TIME;
                    viewmodel.worktime_overname = USERNAME;
                    viewmodel.worktime_status = OwnWorktime[i].WORKTIME_STATUS;
                    ViewOwnworktime.Add(viewmodel);
                }
                #endregion

                Guid myid = new Guid(CurrentUser.UserID);
                var myname = userRepository.Find(r => r.USER_ID == myid).DISPLAY_NAME.ToString();
                ViewBag.myName = myname;
                #region 所有加班记录
                #region 获取该团队空间下的全部人员
                List<UserInfoViewModel> userList = new List<UserInfoViewModel>();//实例化UserInfoViewModel
                //查询出数据库中团队空间ID和当前登录用户的团队ID相等的所有信息
                List<USER_TEAMSAPCE> userTeams = userTeamsapceRepository.GetModel(r => r.TEAMSPACE_ID == teamSpaceId).ToList();
                //根据查出空间团队想的所有信息，再查出所有人的用户ID，放进实例化的UserInfoViewModel表中
                userList.AddRange((from item in userTeams
                                   select new UserInfoViewModel()
                                   {
                                       UserId = item.USER_ID
                                   }).ToList());
                for (int i = 0; i < userList.Count(); i++)//遍历，每个ID所对应的员工姓名
                {
                    var id = userList[i].UserId;
                    userList[i].UserName = userRepository.GetModel(r => r.USER_ID == id).FirstOrDefault().DISPLAY_NAME;
                }
                TempData["UserList"] = userList;
                #endregion
                #region 获取该团队空间下的全部负责人
                List<UserInfoViewModel> LD = new List<UserInfoViewModel>();//实例化UserInfoViewModel
                //查询出数据库中团队空间ID和当前登录用户的团队ID相等的所有信息
                List<USER_TEAMSAPCE> UserTeams = userTeamsapceRepository.GetModel(r => r.TEAMSPACE_ID == teamSpaceId && r.ROLE_ID == 5).ToList();
                //根据查出空间团队想的所有信息，再查出所有人的用户ID，放进实例化的UserInfoViewModel表中
                LD.AddRange((from item in UserTeams
                             select new UserInfoViewModel()
                             {
                                 UserId = item.USER_ID
                             }).ToList());
                for (int i = 0; i < LD.Count(); i++)//遍历，每个ID所对应的员工姓名
                {
                    var id = LD[i].UserId;
                    LD[i].UserName = userRepository.GetModel(r => r.USER_ID == id).FirstOrDefault().DISPLAY_NAME;
                }
                TempData["User"] = LD;

                #endregion


                for (int i = 0; i < userList.Count; i++)//根据遍历出每个员工ID查出加班-------所有人加班记录
                {
                    Guid id = userList[i].UserId;
                    AllWorktime.AddRange(projectdeskworktimeRepository.GetModel(r => r.WORKTIME_NAMEID == id && r.WORKTIME_STATUS == 1).OrderByDescending(r => r.WORKTIME_TIME).ToList());
                }

                for (int i = 0; i < AllWorktime.Count; i++)//所有加班记录
                {
                    Guid id = AllWorktime[i].WORKTIME_NAMEID;
                    var username = userRepository.Find(r => r.USER_ID == id).DISPLAY_NAME.ToString();
                    Guid ID = AllWorktime[i].WORKTIME_OVERNAME;
                    var USERNAME = "";
                    USER_INFO uerinfo = userRepository.Find(r => r.USER_ID == ID);
                    if (uerinfo != null)
                    {
                        USERNAME = uerinfo.DISPLAY_NAME;
                    }
                    ProjectDeskWorkTimeViewModel viewmodel = new ProjectDeskWorkTimeViewModel();
                    viewmodel.worktime_name = username;
                    viewmodel.worktime_time = AllWorktime[i].WORKTIME_TIME;
                    viewmodel.worktime_cause = AllWorktime[i].WORKTIME_CAUSE;
                    viewmodel.worktime_duration = AllWorktime[i].WORKTIME_DURATION;
                    viewmodel.worktime_quantity = AllWorktime[i].WORKTIME_QUANTITY;////////
                    viewmodel.worktime_howduration = AllWorktime[i].WORKTIME_HOWDURATION;///////
                    viewmodel.worktime_day = AllWorktime[i].WORKTIME_DAY.ToString();
                    viewmodel.worktime_time_time = AllWorktime[i].WORKTIME_TIME_TIME;
                    viewmodel.worktime_status = AllWorktime[i].WORKTIME_STATUS;
                    viewmodel.worktime_overname = USERNAME;
                    ViewAllworktime.Add(viewmodel);//全员加班记录
                }


                #region 校验身份
                ViewBag.IsAdmin = false;
                string[] pathArr = Request.Path.Split('/');
                Guid userGuid = new Guid(CurrentUser.UserID);//找到用户登录ID
                USER_INFO user = userRepository.GetModel(r => r.USER_ID == userGuid).FirstOrDefault();//根据用户登录ID 通过员工表 查出此员工信息
                USER_TEAMSAPCE userTeam = userTeamsapceRepository.GetModel(r => r.USER_ID == user.USER_ID).FirstOrDefault();//根据员工的ID 通过团队空间表  查出此人的团队空间信息
                ROLE_INFO role = roleRepository.GetModel(r => r.ROLE_ID == userTeam.ROLE_ID).FirstOrDefault();//根据此人全队空间表信息的团队空间权限ID，查出此人在权限表的信息
                List<MENU_ROLE> menuRole = menuRoleRepository.GetModel(r => r.ROLE_ID == role.ROLE_ID).ToList();//根据此人在权限表的信息中的权限ID，查出此人的菜单表信息
                for (int i = 0; i < menuRole.Count(); i++)
                {
                    int menuId = menuRole[i].MENU_ID;
                    MENU menu = menuRepository.GetModel(r => r.MENU_ID == menuId).FirstOrDefault();//根据菜单Id找此人菜单表的所有信息
                    if (menu.AREA_NAME == pathArr[2] && menu.CONTROLLER_NAME == pathArr[3])
                    {
                        ViewBag.IsAdmin = true;
                        break;
                    }
                }
                #endregion
                ViewBag.anonymity = true;

                #endregion


                #region 登录用户待审批的加班记录
                Guid overid = new Guid(CurrentUser.UserID);

                OverWorkTime = projectdeskworktimeRepository.GetModel(r => r.WORKTIME_OVERNAME == overid && r.WORKTIME_STATUS == 0).ToList();
                if (OverWorkTime.Count > 0)
                {
                    foreach (PROJECT_DESK_WORKTIME over in OverWorkTime)
                    {
                        ProjectDeskWorkTimeViewModel MODEL = new ProjectDeskWorkTimeViewModel();

                        Guid DaiID = over.WORKTIME_NAMEID;
                        var DaiName = userRepository.Find(r => r.USER_ID == DaiID).DISPLAY_NAME.ToString();//加班人姓名
                        Guid DaiId = over.WORKTIME_OVERNAME;
                        var Dainame = userRepository.Find(r => r.USER_ID == DaiId).DISPLAY_NAME.ToString();//审阅人姓名

                        MODEL.worktime_cause = over.WORKTIME_CAUSE;
                        MODEL.worktime_day = over.WORKTIME_DAY.ToString();
                        MODEL.worktime_duration = over.WORKTIME_DURATION;
                        MODEL.worktime_howduration = over.WORKTIME_HOWDURATION;
                        MODEL.worktime_id = over.WORKTIME_ID;
                        MODEL.worktime_name = DaiName;
                        MODEL.worktime_nameid = over.WORKTIME_NAMEID;
                        MODEL.worktime_overname = Dainame;
                        MODEL.worktime_quantity = over.WORKTIME_QUANTITY;
                        MODEL.worktime_status = over.WORKTIME_STATUS;
                        MODEL.worktime_time = over.WORKTIME_TIME;
                        MODEL.worktime_time_time = over.WORKTIME_TIME_TIME;


                        ViewOverWorkTime.Add(MODEL);
                    }
                }
                #endregion





            }
            else   //如果是匿名用户
            {
                AllWorktime = projectdeskworktimeRepository.GetModel(r => r.WORKTIME_STATUS == 1).OrderByDescending(r => r.WORKTIME_TIME).ToList();
                for (int i = 0; i < AllWorktime.Count; i++)
                {
                    Guid id = AllWorktime[i].WORKTIME_NAMEID;
                    var username = userRepository.Find(r => r.USER_ID == id).DISPLAY_NAME.ToString();
                    ProjectDeskWorkTimeViewModel viewmodel = new ProjectDeskWorkTimeViewModel();
                    viewmodel.worktime_name = username;
                    viewmodel.worktime_time = AllWorktime[i].WORKTIME_TIME;
                    viewmodel.worktime_cause = AllWorktime[i].WORKTIME_CAUSE;
                    viewmodel.worktime_duration = AllWorktime[i].WORKTIME_DURATION;
                    viewmodel.worktime_quantity = AllWorktime[i].WORKTIME_QUANTITY;//////////////////////
                    viewmodel.worktime_howduration = AllWorktime[i].WORKTIME_HOWDURATION;//////////////////////////
                    viewmodel.worktime_day = AllWorktime[i].WORKTIME_DAY.ToString();
                    viewmodel.worktime_time_time = AllWorktime[i].WORKTIME_TIME_TIME;
                    ViewAllworktime.Add(viewmodel);
                    ViewBag.anonymity = false;
                    ViewBag.IsAdmin = true;
                }
            }
            #endregion







            ViewBag.ownWorktime = ViewOwnworktime;
            ViewBag.allWorktime = ViewAllworktime;
            ViewBag.daiWorktime = ViewOverWorkTime;
            ViewData["totalExecute"] = ViewOwnworktime.Count;//个人加班集合个数
            ViewData["totalFinish"] = ViewAllworktime.Count;//全员加班个数

            return View();//返回给视图

        }

        /// <summary>
        /// 加班申请
        /// </summary>
        /// <returns></returns>
        public ActionResult ApplyForWorkTime(FormCollection collection)
        {
            #region 计算本月时间
            int year = DateTime.Now.Year;//当前年
            int mouth = DateTime.Now.Month;//当前月
            int beforeYear = 0;
            int BeforeMouth = 0;
            if (mouth <= 1)//如果当前月是1月份，那么现在年份-1
            {
                beforeYear = year - 1;
                BeforeMouth = 12;
            }
            else
            {
                beforeYear = year;
                BeforeMouth = mouth - 1;
            }
            DateTime beforeMouthOneDay = Convert.ToDateTime(beforeYear + "-" + mouth + "-" + 1);//本月月的第一天
            DateTime beforeMouthLastDay = Convert.ToDateTime(beforeYear + "-" + mouth + "-" + DateTime.DaysInMonth(year, mouth));//本月的最后一天
            #endregion

            try
            {
                //int HOWDURATION = 0;
                //Guid id = new Guid(CurrentUser.UserID);
                ////查出符合本月的，登录者的所有请假的集合个数
                //List<PROJECT_DESK_WORKTIME> x = projectdeskworktimeRepository.GetModel(r => r.WORKTIME_NAMEID == id && r.WORKTIME_TIME > beforeMouthOneDay && r.WORKTIME_TIME <= beforeMouthLastDay ).ToList();
                //if (x.Count > 0)//如果本月有加班
                //{
                //    foreach (PROJECT_DESK_WORKTIME howduration in x)
                //    {
                //        HOWDURATION += Convert.ToInt32(howduration.WORKTIME_DURATION);//得到所有加班的时间总和
                //    }
                //}




                int timelong = 0;
                timelong = Convert.ToInt32(collection["select_worktime_timeD"]) - Convert.ToInt32(collection["select_worktime_timeK"]);
                PROJECT_DESK_WORKTIME worktime = new PROJECT_DESK_WORKTIME();

                worktime.WORKTIME_DAY = Convert.ToDateTime(collection["tb_DeadTime"]);
                worktime.WORKTIME_NAMEID = new Guid(CurrentUser.UserID);
                worktime.WORKTIME_TIME = DateTime.Now;
                worktime.WORKTIME_ID = Guid.NewGuid();
                worktime.WORKTIME_CAUSE = collection["tb_worktime_cause"];
                worktime.WORKTIME_DURATION = timelong.ToString(); 
                //worktime.WORKTIME_QUANTITY = x.Count + 1;//加班次数
                worktime.WORKTIME_QUANTITY = 0;



                worktime.WORKTIME_STATUS = 0;
                worktime.WORKTIME_TIME_TIME = collection["select_worktime_timeK"] + ":00" + "-" + collection["select_worktime_timeD"] + ":00";
                //worktime.WORKTIME_HOWDURATION = (HOWDURATION + timelong).ToString(); //加班累计时长      等于本次的加班总时长等于之前的总和加上本次的时长
                worktime.WORKTIME_HOWDURATION = "0";
                worktime.WORKTIME_OVERNAME = new Guid(collection["select_WorkLeader"]);
                projectdeskworktimeRepository.Insert(worktime);

                return RedirectToAction("Index", "Overtime", new { area = "DepartmentArea", flagInfo = "申请成功！", flag = "True" });
            }
            catch (Exception ex)
            {
                return RedirectToAction("Index", "Overtime", new { area = "DepartmentArea", flag = "False", info = ex.Message });
            }


        }


        /// <summary>
        /// 修改加班
        /// </summary> 
        /// <returns></returns>
        public ActionResult updat_worktime(FormCollection collection)
        {

            try
            {
                #region 修改后  根据之前的累计时长 计算出本次修改后加班的累计时长并改变（和次数没关系）
      
                PROJECT_DESK_WORKTIME model = new PROJECT_DESK_WORKTIME();
                model.WORKTIME_ID = new Guid(collection["td_worktime_id"]);
                PROJECT_DESK_WORKTIME old = projectdeskworktimeRepository.GetModel(r => r.WORKTIME_ID == model.WORKTIME_ID).FirstOrDefault();//被修改的记录
                #region 砍掉
                //被修改记录的那个月的第一天    并找出修改记录的那个月中小于被修改的加班记录大于那个月第一天的加班记录(之前不变的)
                //DateTime timeZQ = Convert.ToDateTime(old.WORKTIME_TIME.Year + "-" + old.WORKTIME_TIME.Month + "-" + 1);
                //List<PROJECT_DESK_WORKTIME> updatZQ = projectdeskworktimeRepository.GetModel(r => r.WORKTIME_NAMEID == old.WORKTIME_NAMEID && r.WORKTIME_TIME > timeZQ && r.WORKTIME_TIME < old.WORKTIME_TIME).ToList();

                //int howduration = 0;  //被修改记录之前的加班累计时长
                //if (updatZQ.Count > 0)
                //{
                //    foreach (PROJECT_DESK_WORKTIME y in updatZQ)
                //    {
                //        howduration += Convert.ToInt32(y.WORKTIME_HOWDURATION);
                //    }
                //}
                #endregion
                int timelong = 0;
                timelong = Convert.ToInt32(collection["tb_worktime_timeD"]) - Convert.ToInt32(collection["tb_worktime_timeK"]);//本次修改后的加班时长

                model.WORKTIME_CAUSE = collection["tb_worktime_cause"] == "" ? old.WORKTIME_CAUSE : collection["tb_worktime_cause"];
                model.WORKTIME_DURATION = timelong.ToString();
                model.WORKTIME_QUANTITY = old.WORKTIME_QUANTITY;
                model.WORKTIME_TIME = old.WORKTIME_TIME;
                model.WORKTIME_NAMEID = old.WORKTIME_NAMEID;
                model.WORKTIME_ID = old.WORKTIME_ID;
                //model.WORKTIME_HOWDURATION = (howduration + timelong).ToString();   //累积时长

                model.WORKTIME_HOWDURATION = "0";
                model.WORKTIME_STATUS = old.WORKTIME_STATUS;
                model.WORKTIME_TIME_TIME = collection["tb_worktime_timeK"] + ":00" + "-" + collection["tb_worktime_timeD"] + ":00";
                model.WORKTIME_DAY = Convert.ToDateTime(collection["tb_worktime_DeadTime"]);
                model.WORKTIME_OVERNAME = new Guid(collection["tb_WorkLeader"]);
                projectdeskworktimeRepository.Update(model);
                #endregion

                #region 再次查询修改后的加班， 以修改后的加班累计时长为起点，遍历修改此次加班后的所有加班累计时长  砍掉
                //List<PROJECT_DESK_WORKTIME> LIST = new List<PROJECT_DESK_WORKTIME>(); //修改后，要被修改的记录集合
                //PROJECT_DESK_WORKTIME againSelcet = projectdeskworktimeRepository.GetModel(r => r.WORKTIME_ID == model.WORKTIME_ID).FirstOrDefault();//再次查询一遍修改后的加班记录
                ////被修改记录那个月的最后一天  并找出修改记录的那个月中大于被修改的加班记录小于那个月最后一天的加班记录(这个记录之后的要变的)
                //DateTime timeZH = Convert.ToDateTime(old.WORKTIME_TIME.Year + "-" + old.WORKTIME_TIME.Month + "-" + DateTime.DaysInMonth(old.WORKTIME_TIME.Year, old.WORKTIME_TIME.Month));
                //List<PROJECT_DESK_WORKTIME> updatZH = projectdeskworktimeRepository.GetModel(r => r.WORKTIME_NAMEID == old.WORKTIME_NAMEID && r.WORKTIME_TIME > old.WORKTIME_TIME && r.WORKTIME_TIME <= timeZH  ).OrderBy(r => r.WORKTIME_TIME).ToList();

                //int againselcet = Convert.ToInt32(againSelcet.WORKTIME_HOWDURATION);
                //if (updatZH.Count > 0)
                //{
                //    foreach (PROJECT_DESK_WORKTIME y in updatZH)
                //    {
                //        PROJECT_DESK_WORKTIME list = new PROJECT_DESK_WORKTIME();
                //        list.WORKTIME_CAUSE = y.WORKTIME_CAUSE;
                //        list.WORKTIME_DURATION = y.WORKTIME_DURATION;
                //        list.WORKTIME_ID = y.WORKTIME_ID;
                //        list.WORKTIME_NAMEID = y.WORKTIME_NAMEID;
                //        list.WORKTIME_TIME = y.WORKTIME_TIME;
                //        list.WORKTIME_QUANTITY = y.WORKTIME_QUANTITY;
                //        list.WORKTIME_HOWDURATION = (againselcet + Convert.ToInt32(y.WORKTIME_DURATION)).ToString();//根据被修改后的时长作为起点
                //        againselcet = againselcet + Convert.ToInt32(y.WORKTIME_DURATION);

                //        list.WORKTIME_DAY = y.WORKTIME_DAY;
                //        list.WORKTIME_TIME_TIME = y.WORKTIME_TIME_TIME;
                //        list.WORKTIME_OVERNAME = y.WORKTIME_OVERNAME;
                //        list.WORKTIME_STATUS = y.WORKTIME_STATUS;
                //        LIST.Add(list);
                //    }
                //}
                //projectdeskworktimeRepository.Update(LIST);
                #endregion


                return RedirectToAction("Index", "Overtime", new { area = "DepartmentArea", flagInfo = "修改成功！", flag = "True" });
            }
            catch (Exception ex)
            {
                return RedirectToAction("Index", "Overtime", new { area = "DepartmentArea", flag = "False", flagInfo = "修改失败！" + ex.Message });
            }
        }




        /// <summary>
        /// 删除加班
        /// </summary>
        /// <returns></returns>
        public ActionResult delete_Worktime(FormCollection collection)
        {

            try
            {
                PROJECT_DESK_WORKTIME model = new PROJECT_DESK_WORKTIME();
                model.WORKTIME_ID = new Guid(collection["delete_worktime_idd"]);

                PROJECT_DESK_WORKTIME delete = projectdeskworktimeRepository.GetModel(r => r.WORKTIME_ID == model.WORKTIME_ID).FirstOrDefault(); //被删除的加班记录
                #region 砍掉
                //List<PROJECT_DESK_WORKTIME> LIST = new List<PROJECT_DESK_WORKTIME>(); //删除后，要被修改的记录集合
                ////被删除记录那个月的最后一天  并找出删除记录的那个月中大于被删除的加班记录小于那个月最后一天的加班记录(这个记录之后的要变的)
                //DateTime timeZH = Convert.ToDateTime(delete.WORKTIME_TIME.Year + "-" + delete.WORKTIME_TIME.Month + "-" + DateTime.DaysInMonth(delete.WORKTIME_TIME.Year, delete.WORKTIME_TIME.Month));
                //List<PROJECT_DESK_WORKTIME> updatZH = projectdeskworktimeRepository.GetModel(r => r.WORKTIME_NAMEID == delete.WORKTIME_NAMEID && r.WORKTIME_TIME > delete.WORKTIME_TIME && r.WORKTIME_TIME <= timeZH).OrderBy(r => r.WORKTIME_TIME).ToList();
                ////被删除记录的那个月的第一天    并找出删除记录的那个月中小于被删除的加班记录大于那个月第一天的加班记录(之前不变的)
                //DateTime timeZQ = Convert.ToDateTime(delete.WORKTIME_TIME.Year + "-" + delete.WORKTIME_TIME.Month + "-" + 1);
                //List<PROJECT_DESK_WORKTIME> updatZQ = projectdeskworktimeRepository.GetModel(r => r.WORKTIME_NAMEID == delete.WORKTIME_NAMEID && r.WORKTIME_TIME > timeZQ && r.WORKTIME_TIME < delete.WORKTIME_TIME).ToList();

                //int cishu = 0;//被删除记录的上一条记录的加班次数
                //int howduration = 0;  //被删除记录的上一条记录的加班时长
                //if (updatZQ.Count > 0)
                //{
                //    foreach (PROJECT_DESK_WORKTIME y in updatZQ)
                //    {
                //        howduration += Convert.ToInt32(y.WORKTIME_HOWDURATION);
                //    }
                //    cishu = updatZQ.Count;
                //}
                //if (updatZH.Count > 0)
                //{
                //    foreach (PROJECT_DESK_WORKTIME y in updatZH)
                //    {
                //        PROJECT_DESK_WORKTIME list = new PROJECT_DESK_WORKTIME();
                //        list.WORKTIME_CAUSE = y.WORKTIME_CAUSE;
                //        list.WORKTIME_DURATION = y.WORKTIME_DURATION;
                //        list.WORKTIME_ID = y.WORKTIME_ID;
                //        list.WORKTIME_NAMEID = y.WORKTIME_NAMEID;
                //        list.WORKTIME_TIME = y.WORKTIME_TIME;
                //        list.WORKTIME_QUANTITY = cishu + 1;
                //        cishu = cishu + 1;
                //        list.WORKTIME_HOWDURATION = (howduration + Convert.ToInt32(y.WORKTIME_DURATION)).ToString();

                //        list.WORKTIME_TIME_TIME = y.WORKTIME_TIME_TIME;
                //        list.WORKTIME_DAY = y.WORKTIME_DAY;
                //        list.WORKTIME_OVERNAME = y.WORKTIME_OVERNAME;
                //        list.WORKTIME_STATUS = y.WORKTIME_STATUS;


                //        howduration = howduration + Convert.ToInt32(y.WORKTIME_DURATION);
                //        LIST.Add(list);
                //    }
                //}

                #endregion

                projectdeskworktimeRepository.Delete(delete);
                //projectdeskworktimeRepository.Update(LIST); //砍掉
                return RedirectToAction("Index", "Overtime", new { area = "DepartmentArea", flagInfo = "删除成功！", flag = "True" });
            }
            catch (Exception ex)
            {

                return RedirectToAction("Index", "Overtime", new { area = "DepartmentArea", flag = "False", flagInfo = "删除失败！" + ex.Message });
            }

        }




        /// <summary>
        /// 审批的提交方法
        /// </summary> 
        /// <returns></returns>
        public ActionResult S_worktime(FormCollection collection)
        {
            #region 计算本月时间
            int year = DateTime.Now.Year;//当前年
            int mouth = DateTime.Now.Month;//当前月
            int beforeYear = 0;
            int BeforeMouth = 0;
            if (mouth <= 1)//如果当前月是1月份，那么现在年份-1
            {
                beforeYear = year - 1;
                BeforeMouth = 12;
            }
            else
            {
                beforeYear = year;
                BeforeMouth = mouth - 1;
            }
            DateTime beforeMouthOneDay = Convert.ToDateTime(beforeYear + "-" + mouth + "-" + 1);//本月月的第一天
            DateTime beforeMouthLastDay = Convert.ToDateTime(beforeYear + "-" + mouth + "-" + DateTime.DaysInMonth(year, mouth));//本月的最后一天
            #endregion

      
            try
            {
                int HOWDURATION = 0;
                Guid id = new Guid(collection["dai_worktime_idd"]);
                PROJECT_DESK_WORKTIME work = projectdeskworktimeRepository.GetModel(r => r.WORKTIME_ID == id).FirstOrDefault();




                DateTime timeZQ = Convert.ToDateTime(work.WORKTIME_TIME.Year + "-" + work.WORKTIME_TIME.Month + "-" + 1);//此次申请加班那个月的第一天
                DateTime timeZH = Convert.ToDateTime(work.WORKTIME_TIME.Year + "-" + work.WORKTIME_TIME.Month + "-" + DateTime.DaysInMonth(work.WORKTIME_TIME.Year, work.WORKTIME_TIME.Month));//此次申请加班那个月的最后一天
                //查出符合那个月的，登录者的所有审批通过的集合
                List<PROJECT_DESK_WORKTIME> x = projectdeskworktimeRepository.GetModel(r => r.WORKTIME_NAMEID == work.WORKTIME_NAMEID && r.WORKTIME_TIME > timeZQ && r.WORKTIME_TIME <= timeZH&&r.WORKTIME_STATUS==1).ToList();
                if (x.Count > 0)//如果本月有加班
                {
                    foreach (PROJECT_DESK_WORKTIME howduration in x)
                    {
                        HOWDURATION += Convert.ToInt32(howduration.WORKTIME_DURATION);//得到所有加班的时间总和
                    }
                }
                PROJECT_DESK_WORKTIME WORK = new PROJECT_DESK_WORKTIME();

                WORK.WORKTIME_CAUSE = work.WORKTIME_CAUSE;
                WORK.WORKTIME_DAY = work.WORKTIME_DAY;
                WORK.WORKTIME_DURATION = work.WORKTIME_DURATION;
                WORK.WORKTIME_ID = work.WORKTIME_ID;
                WORK.WORKTIME_NAMEID = work.WORKTIME_NAMEID;
                WORK.WORKTIME_OVERNAME = work.WORKTIME_OVERNAME;
                WORK.WORKTIME_TIME = work.WORKTIME_TIME;
                WORK.WORKTIME_TIME_TIME = work.WORKTIME_TIME_TIME;
                WORK.WORKTIME_STATUS =Convert.ToInt32(collection["select_WorkTimeStatus"]);

                //WORK.WORKTIME_QUANTITY = work.WORKTIME_QUANTITY;
                //WORK.WORKTIME_HOWDURATION = work.WORKTIME_HOWDURATION;
                WORK.WORKTIME_QUANTITY = x.Count + 1;
                WORK.WORKTIME_HOWDURATION = (HOWDURATION +Convert.ToInt32(work.WORKTIME_DURATION)).ToString();



                projectdeskworktimeRepository.Update(WORK);
                return RedirectToAction("Index", "Overtime", new { area = "DepartmentArea", flagInfo = "审批成功！", flag = "True" });
            }
            catch (Exception ex)
            {
                return RedirectToAction("Index", "Overtime", new { area = "DepartmentArea", flag = "False", flagInfo = "审批失败！" + ex.Message });
            }
        }











        /// <summary>
        /// ajax 获取一条加班信息
        /// </summary>
        /// <returns></returns>
        public JsonResult OvertimeUpdat(Guid roleId)
        {
            ProjectDeskWorkTimeViewModel model = new ProjectDeskWorkTimeViewModel();
            PROJECT_DESK_WORKTIME role = projectdeskworktimeRepository.GetModel(r => r.WORKTIME_ID == roleId).FirstOrDefault();
            Guid id = role.WORKTIME_NAMEID;
            var username = userRepository.Find(r => r.USER_ID == id).DISPLAY_NAME.ToString();//要权限
            model.worktime_cause = role.WORKTIME_CAUSE;
            model.worktime_duration = role.WORKTIME_DURATION;
            model.worktime_id = role.WORKTIME_ID;
            model.worktime_time_time = role.WORKTIME_TIME_TIME;
            model.worktime_name = username;
            model.worktime_day = role.WORKTIME_DAY.ToString();
            model.worktime_time_time = role.WORKTIME_TIME_TIME;
            return Json(model);
        }



        /// <summary>
        /// ajax 获取要被删除的加班
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public JsonResult documentDelete(Guid roleId)
        {

            ProjectDeskWorkTimeViewModel model = new ProjectDeskWorkTimeViewModel();
            PROJECT_DESK_WORKTIME role = projectdeskworktimeRepository.GetModel(r => r.WORKTIME_ID == roleId).FirstOrDefault();
            model.worktime_id = role.WORKTIME_ID;
            return Json(model);
        }




        /// <summary>
        /// 全员请假查询ajax
        /// </summary>
        /// <param name="NameId"></param>
        /// <param name="BTime"></param>
        /// <param name="DTime"></param>
        /// <returns></returns>
        public JsonResult SelcetS(string NameId, DateTime BTime, DateTime DTime)
        {

            List<ProjectDeskWorkTimeViewModel> list = new List<ProjectDeskWorkTimeViewModel>();
            List<PROJECT_DESK_WORKTIME> model = new List<PROJECT_DESK_WORKTIME>();
            if (NameId != "1")
            {
                Guid NameID = new Guid(NameId);
                model = projectdeskworktimeRepository.GetModel(r =>r.WORKTIME_NAMEID == NameID && r.WORKTIME_DAY >= BTime && r.WORKTIME_DAY <= DTime && r.WORKTIME_STATUS == 1).OrderByDescending(r => r.WORKTIME_TIME).ToList();
            }
            if (NameId == "1")
            {
                model = projectdeskworktimeRepository.GetModel(r => (r.WORKTIME_DAY >= BTime && r.WORKTIME_DAY <= DTime && r.WORKTIME_STATUS == 1)).OrderByDescending(r => r.WORKTIME_TIME).ToList();
            }
            if (model.Count > 0)
            {
                foreach (PROJECT_DESK_WORKTIME x in model)
                {
                    ProjectDeskWorkTimeViewModel pl = new ProjectDeskWorkTimeViewModel();

                    string name = userRepository.GetModel(r => r.USER_ID == x.WORKTIME_NAMEID).FirstOrDefault().DISPLAY_NAME;
                    pl.worktime_name = name;
                    pl.worktime_cause = x.WORKTIME_CAUSE;
                    pl.worktime_day = x.WORKTIME_DAY.ToString("yyyy-MM-dd");
                    if (x.WORKTIME_STATUS == 1)
                    {
                        pl.worktime_status_selcet = "通过";
                    }
                    string overname = userRepository.GetModel(r => r.USER_ID == x.WORKTIME_OVERNAME).FirstOrDefault().DISPLAY_NAME;
                    pl.worktime_overname = overname;
                    pl.worktime_nameid = x.WORKTIME_NAMEID;
                    pl.worktime_id = x.WORKTIME_ID;
                    pl.worktime_quantity = x.WORKTIME_QUANTITY;
                    pl.worktime_time = x.WORKTIME_TIME;
                    pl.worktime_time_time = x.WORKTIME_TIME_TIME;
                    pl.worktime_time_selcet = x.WORKTIME_TIME.ToString("yyyy-MM-dd");
                    pl.worktime_howduration = x.WORKTIME_HOWDURATION;
                    pl.worktime_duration = x.WORKTIME_DURATION;
                    list.Add(pl);
                }
            }

            return Json(list);
        }

    }
}
